export const handleSuccess = (response) => {
  const { data } = response;
  if (typeof data === 'object' && 'code' in data) {
    if (data.code === 0) {
      return data.data;
    } else {
      return Promise.reject({ message: data.message, code: data.code });
    }
  }
  // 非标准格式响应直接返回
  return data;
};

export const handleError = (error) => {
  const errorInfo = {
    message: 'Network error',
    code: -1,
    status: error.response?.status || null
  };

  if (error.response) {
    // 服务器响应错误
    const { data, status } = error.response;
    errorInfo.status = status;
    errorInfo.message = data?.message || `Server error (${status})`;
    errorInfo.code = data?.code || status;
  } else if (error.request) {
    // 无响应错误
    errorInfo.message = 'No response received from server';
  } else {
    // 请求配置错误
    errorInfo.message = error.message || 'Request configuration error';
  }

  return Promise.reject(errorInfo);
};

export const showError = (message) => {
  if (window.toast) {
    window.toast.error(message);
  } else if (window.alert) {
    window.alert(message);
  } else {
    console.error('API Error:', message);
  }
};